<template>
    <div class="container">
        <div class="recordMain" v-if="isRecording">
            <span>录制时长：{{ formatTime(recordingTime) }}</span>
            <el-button type="danger" v-if="isRecording" @click="stopRecording">停止录制</el-button>
        </div>
        <div class="main" v-show="!isRecording">
            <div class="toolBar">
                <el-button type="primary" v-if="sources.length === 0" size="small" @click="getSources">获取窗口</el-button>
                <el-select v-model="currentSource" v-if="sources.length > 0" placeholder="选择要录制的窗口" size="small"
                    style="width: 130px">
                    <el-option v-for="item in sources" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
                <el-button type="primary" v-if="!isRecording" @click="read2record">开始录制</el-button>
                <el-button type="primary" v-if="videoUrl" @click="videoUrl = null">清空</el-button>
                <el-button type="primary" v-if="videoUrl" @click="saveMp4">保存</el-button>
            </div>
            <hr />
            <div class="other">
                <video class="video" v-if="videoUrl" :src="videoUrl" controls></video>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';

const isRecording = ref(false);
const recordedChunks = ref([]);
const mediaRecorder = ref(null);
const videoUrl = ref()
const sources = ref([]);
const currentSource = ref(null);
const recordingTime = ref(0);
const recordingInterval = ref(null);

const getSources = async () => {
    sources.value = await getDesktopCapturerSource(); // 这里返回的是设备上的所有窗口信息
    currentSource.value = sources.value[0].id;
    console.log('sources', sources.value);
    console.log('currentSource', currentSource.value);
}

const getDesktopCapturerSource = async () => {
    return await window.electron.ipcRenderer.invoke("getDesktopCapturerSource", []);
};
const getInitStream = async (source, audio) => {
    return new Promise((resolve, _reject) => {
        // 获取指定窗口的媒体流
        (navigator.mediaDevices)
            .getUserMedia({
                audio: audio
                    ? {
                        mandatory: {
                            chromeMediaSource: "desktop",
                        },
                    }
                    : false,
                video: {
                    mandatory: {
                        chromeMediaSource: "desktop",
                        chromeMediaSourceId: source.id,
                    },
                },
            })
            .then((stream) => {
                resolve(stream);
            })
            .catch((error) => {
                console.log(error);
                resolve(null);
            });
    })
}
const startRecording = async () => {
    try {
        mediaRecorder.value = null
        const stream = await getInitStream(sources.value.filter((e) => {
            return e.id == currentSource.value
        })[0],true);
        mediaRecorder.value = new MediaRecorder(stream);
        recordedChunks.value = []
        mediaRecorder.value.ondataavailable = (event) => {
            recordedChunks.value.push(event.data);
            console.log('recordedChunks.value', recordedChunks.value);
        };

        mediaRecorder.value.onstop = async () => {
            const blob = new Blob(recordedChunks.value, { type: 'video/mp4' });
            videoUrl.value = URL.createObjectURL(blob);
            recordedChunks.value = [];
            console.log('videoUrl.value', videoUrl.value);
        };

        mediaRecorder.value.start();
        isRecording.value = true;

        // 录制时长
        recordingTime.value = 0;
        if(recordingInterval.value) {
            clearInterval(recordingInterval.value);
        }
        recordingInterval.value = setInterval(() => {
            recordingTime.value++;
        }, 1000);
    } catch (error) {
        console.error('Error starting recording:', error);
    }
};
const stopRecording = () => {
    if (mediaRecorder.value) {
        mediaRecorder.value.stop();
        isRecording.value = false;
        window.electron.ipcRenderer.send('finishRecord', JSON.stringify({}));
    }
};
const formatTime = (time) => {
    const hours = Math.floor(time / 3600);
    const minutes = Math.floor((time % 3600) / 60);
    const seconds = time % 60;
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
};

const read2record = () => {
    window.electron.ipcRenderer.send('readyRecord', JSON.stringify({}));
}
const saveMp4 = () => {
    const a = document.createElement('a');
    a.href = videoUrl.value;
    a.download = 'recordedVideo.mp4';
    a.click();
};
onMounted(() => {
    window.electron.ipcRenderer.on('letsfkingRecord', startRecording);
})
</script>

<style lang="less" scoped>
.container {
    width: 100vw;
    height: 100vh;
    padding: 10px;
    position: relative;
    border-radius: 10px;
    overflow: hidden;
    border: 1px solid #333;
    color: #333;
    opacity: 0.9;

    .recordMain {
        width: 100%;
        height: 100%;
        -webkit-app-region: no-drag;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .main {
        width: 100%;
        height: 100%;
        -webkit-app-region: no-drag;
        display: flex;
        flex-direction: column;

        .toolBar {
            width: 100%;
            height: 30px;
        }

        .other {
            flex: 1;

            .video {
                width: 100%;
                height: 100%;
                border-radius: 5px;
            }
        }

    }
}
</style>